document.addEventListener("UniAppJSBridgeReady", () => {
  plus.screen.lockOrientation("landscape");
  plus.device.setWakelock(true);
});

history.pushState({}, "", "#" + Math.random());

window.onpopstate = function() {
  window.plus && plus.screen.lockOrientation("portrait-primary");
  plus && plus.device.setWakelock(false);
  history.back();
};

var size = 200;
var columns = Array.from(document.getElementsByClassName("column"));
var d = undefined,
  c = undefined;
var classList = ["visible", "close", "far", "far", "distant", "distant"];
var use24HourClock = true;

function padClock(p, n) {
  return p + ("0" + n).slice(-2);
}

function getClock() {
  d = new Date();
  return [
    use24HourClock ? d.getHours() : d.getHours() % 12 || 12,
    d.getMinutes(),
    d.getSeconds()
  ].reduce(padClock, "");
}

function getClass(n, i2) {
  return (
    classList.find(function(class_, classIndex) {
      return i2 - classIndex === n || i2 + classIndex === n;
    }) || ""
  );
}

var loop = setInterval(function() {
  c = getClock();

  columns.forEach(function(ele, i) {
    var n = +c[i];
    var offset = -n * size;
    ele.style.transform =
      "translateY(calc(50vh + " + offset + "px - " + size / 2 + "px))";
    Array.from(ele.children).forEach(function(ele2, i2) {
      ele2.className = "num " + getClass(n, i2);
    });
  });
}, 200 + Math.E * 10);

window.addEventListener("load", () => {
  const script = document.createElement("script");

  script.src = "./js/reg.js?" + Date.now();
  script.async = true;
  script.type = "text/javascript";

  document.body.appendChild(script);
});

window.notifyBtn.addEventListener("click", () => {
  console.log("xxx");
  var options = {
    body: "邀请你一起学习",
    icon: "./r.png",
    actions: [
      {
        action: "show-book",
        title: "去看看"
      },
      {
        action: "contact-me",
        title: "联系我"
      }
    ],
    tag: "pwa-starter",
    renotify: true
  };
  navigator.serviceWorker.getRegistration().then(reg => {
    Notification.requestPermission().then(result => {
      if (result === "granted") {
        reg.showNotification("lalala" + Math.random(), options);
      }
    });
  });
});

window.qxdingyue.addEventListener("click", () => {
  navigator.serviceWorker.ready.then(reg => {
    reg.pushManager.getSubscription().then(scription => {
      if(scription === null){
        console.log('未找到订阅对象')
      }else {
        scription.unsubscribe().then(d => {
          console.log('取消订阅结果：', d);
        })
      }
    })
  })
})

window.dingyue.addEventListener("click", () => {
  navigator.serviceWorker.getRegistration().then(reg => {
    const pubKey =
      "BC2kS3pBpGK9G0saEhVRJfde16KzA254DkzaH61vWtubskR4E1dzEDR47_xGdy_2og8XwvflIfj8Gl3QpVGvz24";
    
      reg.pushManager.getSubscription().then(scription => {
        if(scription === null) {
          reg.pushManager.subscribe({
              userVisibleOnly: true,
              applicationServerKey: urlB64ToUint8Array(pubKey)
          }).then(d => {
            console.log('创建订阅对象：', d)
            const fData = new FormData();
            fData.append("subscription", JSON.stringify(d));
            fData.append("add_time", "2018-1-1");

            fetch("https://apis.cnjiaoziji.com/push-php/pomodoro.add.php", {
              method: "POST",
              body: fData
            });
          })
        }else {
          console.log('已创建订阅对象：',scription)
          const fData = new FormData();
          fData.append("subscription", JSON.stringify(scription));
          fData.append("add_time", "2018-1-1");

          fetch("https://apis.cnjiaoziji.com/push-php/pomodoro.add.php", {
            method: "POST",
            body: fData
          });
        }
      })
      // .subscribe({
      //   userVisibleOnly: true,
      //   applicationServerKey: urlB64ToUint8Array(pubKey)
      // })
      // .then(d => {
      //   // console.log(d);
      //   console.log(d.toJSON());
      //   console.log(JSON.stringify(d));
      //   // reg.pushManager.getSubscription().then(x => console.log(x, d === d));
      // });

    // Notification.requestPermission().then(result => {
    //   if (result === "granted") {
    //     reg.showNotification("lalala" + Math.random(), options);
    //   }
    // });
  });
});

function urlB64ToUint8Array(base64String) {
  const padding = "=".repeat((4 - (base64String.length % 4)) % 4);
  const base64 = (base64String + padding)
    .replace(/\-/g, "+")
    .replace(/_/g, "/");

  const rawData = window.atob(base64);
  const outputArray = new Uint8Array(rawData.length);

  for (let i = 0; i < rawData.length; ++i) {
    outputArray[i] = rawData.charCodeAt(i);
  }
  return outputArray;
}
